package com.lg.threadpool;

import com.lg.queue.BlockingQueue;
import com.lg.reject.RejectPolicy;
import lombok.extern.slf4j.Slf4j;

import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义线程池
 */
@Slf4j(topic = "c.com.lg.ThreadPool")
public class ThreadPool {
    /**
     * 任务队列
     */
    private BlockingQueue<Runnable> taskQueue;
    /**
     * 线程集合
     */
    private HashSet<ThreadPool.Worker> workers = new HashSet<>();
    /**
     * 核心线程数
     */
    private int coreSize;
    /**
     * 获取任务的超时时间
     */
    private long timeout;
    /**
     * 时间格式
     */
    private TimeUnit timeUnit;
    /**
     * 阻绝策略
     */
    private RejectPolicy<Runnable> rejectPolicy;
    // 救急线程数
    private int emergencySize = 2;


    // 线程name
    private String threadName = "thread-pool-";

    private AtomicInteger count = new AtomicInteger(0);


    /**
     * 执行任务
     *
     * @param task
     */
    public void execute(Runnable task) {
        // 当任务数没有超过 coreSize 时，直接交给 worker 对象执行
        // 如果任务数超过 coreSize 时，加入任务队列暂存
        synchronized (workers) {
            if (workers.size() < coreSize) {
                ThreadPool.Worker worker = new ThreadPool.Worker(task, threadName + count.getAndIncrement());
                log.debug("新增 worker {} ，{}", worker, task);
                workers.add(worker);
                worker.start();
            } else {
                if (taskQueue.size() >= taskQueue.getCapacity() && taskQueue.size() < taskQueue.getCapacity() + emergencySize) {
                    // 启动救急策略
                    log.debug("阻塞队列已满，启动救急线程...");
                    ThreadPool.Worker worker = new ThreadPool.Worker(task, threadName + count.getAndIncrement());
                    log.debug("新增救急线程 worker {} ，{}", worker, task);
                    workers.add(worker);
                    worker.start();
                } else {
                    //                taskQueue.put(task);
                    // 1) 死等
                    // 2) 带超时等待
                    // 3) 让调用者放弃任务执行
                    // 4) 让调用者抛出异常
                    // 5) 让调用者自己执行任务
                    taskQueue.tryPut(rejectPolicy, task); // 使用策略模式，将所有的操作都封装到 接口中，交由子类具体实现
                }

            }
        }
    }

    public ThreadPool(int queueCapacity,
                      int coreSize, long timeout, TimeUnit timeUnit,
                      RejectPolicy<Runnable> rejectPolicy) {
        this.taskQueue = new BlockingQueue(queueCapacity);
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.rejectPolicy = rejectPolicy;
    }

    /**
     * 工作线程
     */
    private class Worker extends Thread {
        private Runnable task;
        private String threadName;

        public Worker(Runnable task, String threadName) {
            this.task = task;
            this.threadName = threadName;
        }

        @Override
        public void run() {
            Thread.currentThread().setName(threadName);
            // 指定任务
            // 1. 当 task不为空，执行任务
            // 2. 当task 执行完毕，再接着从任务队列获取任务并执行
            while (task != null || (task = taskQueue.poll(timeout, timeUnit)) != null) {
                try {
                    log.debug("正在执行... {}", task);
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }
            }
            synchronized (workers) { // 当任务都执行完毕之后，将工作线程 shutdown
                log.debug("worker 被移除{}", this);
                workers.remove(this);
            }
        }
    }
}
